package com.monkey.tensquare.article.service.impl;

import com.monkey.tensquare.article.entity.Article;
import com.monkey.tensquare.article.mapper.ArticleMapper;
import com.monkey.tensquare.article.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void add(Article article) {
        article.setId(idWorker.nextId() + "");
        articleMapper.save(article);
    }

    @Override
    public List<Article> findAll() {
        return articleMapper.findAll();
    }

    @Override
    public Article findById(String articleId) {
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        System.out.println(article);
        if (article == null) {
            article = articleMapper.findById(articleId).get();
            redisTemplate.opsForValue().set("article_" + articleId,article);
        }
        return article;
    }
    // 更新文章
    @Override
    public void update(String articleId, Article article) {
        // 先从redis中删除
        redisTemplate.delete("article_" + articleId);
        // 再更新数据库
        article.setId(articleId);
        articleMapper.save(article);
    }

    @Override
    public void delete(String articleId) {
        // 先从redis中删除
        redisTemplate.delete("article_" + articleId);
        // 再从数据库数据库删除
        articleMapper.deleteById(articleId);
    }
}
